/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 5/21/18
Time: 5:17 PM
 */

package Cn.Sarkar.ResponseModels

import io.ktor.application.ApplicationCall
import io.ktor.http.HttpStatusCode
import io.ktor.pipeline.PipelineContext
import io.ktor.response.respond
import java.io.PrintWriter
import java.io.StringWriter


data class Success(var success: Boolean = false, var message: String = "", var exception: String = "")

inline suspend fun <TSubject : Any, TContext : ApplicationCall, reified RETURNVAL> PipelineContext<TSubject, TContext>.success(error: HttpStatusCode = HttpStatusCode.InternalServerError, action: () -> RETURNVAL) = try {
    val message = action()
    val result = Success(true)
    if (message is String) result.message = message
    context.respond(result)
} catch (exception: Exception) {
    exception.printStackTrace()
    context.response.status(error)

//    val writer = StringWriter()
//    val printWriter = PrintWriter(writer)
//    exception.printStackTrace(printWriter)
//    val message = writer.toString()
//    printWriter.close()
//    writer.close()

    context.respond(Success(false, exception.message ?: "", exception::class.java.name))
}